import { FC, useState, useEffect } from 'react'
import { useRouter } from 'next/router'
import { BookOpen } from 'lucide-react'

interface QuizProps {
  // 可根据需要扩展其他 props
}

// 更新 QuizQuestion 接口以匹配后端返回格式
interface QuizQuestion {
  question_id: string
  question_text: string
  options: {
    A: string
    B: string
    C: string
    D: string
  }
  correct_answer: string
  explanation: string
  difficulty: string
  knowledge_points: string[]
}

// 更新 QuizResponse 接口以匹配后端返回格式
interface QuizResponse {
  quizzes: {
    total_questions: number
    questions: QuizQuestion[]
  }
}

const Quiz: FC<QuizProps> = () => {
  const router = useRouter()
  const { id } = router.query // 获取路由中的id参数

  // 添加路由准备状态检查
  const [isRouterReady, setIsRouterReady] = useState(false)
  const [videoUrl, setVideoUrl] = useState('')
  const [questionCount, setQuestionCount] = useState(4) // 默认生成4道题目

  const [quizData, setQuizData] = useState<QuizQuestion[]>([])
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')

  useEffect(() => {
    if (router.isReady) {
      setIsRouterReady(true)

      // 如果有id参数，从localStorage中获取视频信息
      if (id) {
        const learningData = localStorage.getItem(`learning_${id}`)
        if (learningData) {
          try {
            const parsedData = JSON.parse(learningData)
            if (parsedData.url) {
              setVideoUrl(parsedData.url)
              console.log('从localStorage获取到视频URL:', parsedData.url)
            }
          } catch (error) {
            console.error('解析localStorage数据失败:', error)
            setError('获取视频信息失败')
          }
        } else {
          console.error('未找到视频信息:', id)
          setError('未找到视频信息')
        }
      }
    }
  }, [router.isReady, id])

  // 更新生成选择题的处理函数
  const handleGenerateQuiz = async () => {
    if (!videoUrl) {
      setError('请先输入视频 URL')
      return
    }
    setError('')
    setLoading(true)

    try {
      console.log('Sending request to backend with URL:', videoUrl)

      const response = await fetch('http://127.0.0.1:8000/quiz', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          url: videoUrl,
          cookie: '',
        }),
      })

      if (!response.ok) {
        const errorData = await response.text()
        console.error('Backend error:', errorData)
        throw new Error(`生成题目失败: ${errorData}`)
      }

      const data = await response.json()
      console.log('Received quiz data:', data)

      // 检查返回的数据结构并正确处理
      if (data.quizzes && data.quizzes.questions && Array.isArray(data.quizzes.questions)) {
        setQuizData(data.quizzes.questions)
      } else if (data.questions && Array.isArray(data.questions)) {
        setQuizData(data.questions)
      } else if (Array.isArray(data)) {
        // 如果直接返回问题数组
        setQuizData(data)
      } else {
        throw new Error('返回数据格式不正确')
      }
    } catch (err) {
      console.error('生成题目出错:', err)
      setError(err instanceof Error ? err.message : '生成题目失败，请重试')
    } finally {
      setLoading(false)
    }
  }

  // 如果路由未准备好，显示加载状态
  if (!isRouterReady) {
    return <div className="p-4">加载中...</div>
  }

  return (
    <div className="p-4">
      {/* 页面标题 */}
      <h2 className="mb-4 flex items-center gap-2 text-xl font-bold">
        <BookOpen className="h-5 w-5" />
        AI出题
      </h2>

      {/* 操作按钮区域：只保留生成选择题按钮 */}
      <div className="my-4 flex gap-4">
        <button
          onClick={handleGenerateQuiz}
          disabled={loading}
          className="rounded bg-blue-500 px-4 py-2 text-white hover:bg-blue-600"
        >
          {loading ? '生成中，请稍候...' : '生成选择题'}
        </button>
      </div>

      {/* 错误提示 */}
      {error && <p className="mt-4 text-red-500">{error}</p>}

      {/* 选择题展示区域 */}
      {quizData.length > 0 && (
        <div className="mt-6 space-y-6">
          <h3 className="mb-4 text-xl font-bold">选择题</h3>
          {quizData.map((quiz, idx) => (
            <div key={idx} className="rounded border p-4">
              <p className="mb-4 text-lg font-semibold">
                题目 {idx + 1}: {quiz.question_text}
              </p>
              <div className="flex space-x-4">
                {Object.entries(quiz.options).map(([key, value]) => (
                  <button
                    key={key}
                    className={`flex-1 rounded border px-2 py-1 text-sm ${
                      quiz.correct_answer === key ? 'border-green-600 bg-green-300 font-bold' : 'bg-gray-100'
                    }`}
                  >
                    {key}. {value}
                  </button>
                ))}
              </div>
              {/* 添加解析显示 */}
              <div className="mt-3 rounded bg-gray-50 p-3 text-sm">
                <p className="font-semibold">解析：</p>
                <p>{quiz.explanation}</p>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  )
}

export default Quiz
